<template>
  <div class="edit-print">
    <el-form label-width="60px">
      <header class="headertool">
        <el-button
          type="success"
          size="medium"
          icon="el-icon-finished"
          @click="Save"
        >保存</el-button>
        <el-button
          type="info"
          size="medium"
          icon="el-icon-refresh-left"
          @click="Reset"
        >重置</el-button>
        <el-button
          type="primary"
          size="medium"
          icon="el-icon-printer"
          @click="printPreview()"
        >打印预览</el-button>
      </header>
      <div class="mainBox">
        <div id="mainBox_left" class="mainBox_child mainBox_left">
          <el-card class="paddingcard">
            <div slot="header">
              <span style="line-height: 25px;">常用字段</span>
              <span style="position: absolute; top: 15px; right: 20px;">
                <el-input
                  v-model="form.addCustom"
                  placeholder="自定义字段"
                  class="mainBox_left_minInput"
                  size="small"
                />
                <el-tooltip class="item" effect="dark" content="将该字段添加到表格中" placement="top-start">
                  <el-button icon="el-icon-d-arrow-right" size="mini" circle type="primary" @click="addCustom" />
                </el-tooltip>

              </span>
            </div>
            <div class="customButtonGroup">
              <template v-for="(item, index) in listData">
                <el-divider
                  :key="index"
                  content-position="left"
                >{{ item.itemName }}</el-divider>
                <template v-for="(itemchild, index2) in item.itemInfo">
                  <el-button
                    :key="index2"
                    type="info"
                    size="mini"
                    round
                    class="customButton"
                    @click="handleCustomButton(itemchild)"
                  >{{ itemchild.label }}</el-button>
                </template>
              </template>
            </div>
          </el-card>
        </div>
        <div v-loading="loading" class="mainBox_child mainBox_in" element-loading-text="模板加载中">
          <div id="editor" />
        </div>
        <div class="mainBox_child mainBox_right">
          <el-card>
            <div slot="header" class="mainBox_header">
              <span>模板设置</span>
              <el-button type="text" style="float: right; padding: 5px;" @click="handleTableReSize">应用尺寸</el-button>
            </div>
            <div>
              <el-form-item label="毫米">
                <el-input
                  v-model="tableModel.mmWidth"
                  placeholder="宽"
                  maxlength="4"
                  class="mainBox_left_minInput"
                >
                  <template slot="append">宽</template>
                </el-input>

                <el-input
                  v-model="tableModel.mmHeight"
                  placeholder="高"
                  maxlength="4"
                  class="mainBox_left_minInput"
                >
                  <template slot="append">高</template>
                </el-input>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="像素">
                <el-input
                  v-model="tableModel.pxWidth"
                  placeholder="宽"
                  maxlength="4"
                  disabled
                  class="mainBox_left_minInput"
                >
                  <template slot="append">宽</template>
                </el-input>

                <el-input
                  v-model="tableModel.pxHeight"
                  placeholder="高"
                  maxlength="4"
                  disabled
                  class="mainBox_left_minInput"
                >
                  <template slot="append">高</template>
                </el-input>
              </el-form-item>
            </div>
          </el-card>
          <transition name="fade">
            <el-card v-show="tableSelectTipShow" class="paddingcard">
              <div slot="header">
                <span>表格属性</span>
              </div>
              <div>
                <el-form :inline="true" label-width="100px" label-position="left">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="字体大小(px)" class="miniInput">
                        <el-input v-model="tableSet.fontSize" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="行高(mm)" class="miniInput">
                        <el-input v-model="tableSet.lineHeight" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="上边距(mm)" class="miniInput">
                        <el-input v-model="tableSet.marginTop" />
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="左边距(mm)" class="miniInput">
                        <el-input v-model="tableSet.marginLeft" />
                      </el-form-item>
                    </el-col>
                    <div class="otherLable_chikd">
                      <el-form-item label="显示边框">
                        <el-radio
                          v-model="tableSet.border"
                          label="1"
                        >是</el-radio>
                        <el-radio
                          v-model="tableSet.border"
                          label="0"
                        >否</el-radio>
                      </el-form-item>
                    </div>

                    <el-form-item label="表格列占比例" class="miniInput">
                      <el-input v-model="tableSet.Proportion" disabled />
                    </el-form-item>
                  </el-row>
                </el-form>
              </div>
            </el-card>
          </transition>
        </div>
      </div>
    </el-form>
    <el-dialog
      :visible.sync="dialogPrintPreview"
      top="10px"
      :width="tableModel.pxWidth+40+'px'"
    >
      <canvas
        id="panel"
        :height="tableModel.pxHeight"
        :width="tableModel.pxWidth"
      />
    </el-dialog>
  </div>
</template>

<script type="text/javascript" src="/print/ckeditor/ckeditor.js"></script>
<script src="/print/js/htmlCompile.js"></script>
<script src="/print/js/print/print-util.js"></script>
<script>
  import { BeeDraw } from '@/utils/print-util.js'
  import { getPrinterType, updatePrinterType } from '@/api'
  export default {
    name: 'editPrint',
    data() {
      return {
        loading: false,
        dialogPrintPreview: false,
        tableModel: {
          mmWidth: '0',
          mmHeight: '0'
        },
        editor: '',
        form: {},
        listData: [],
        tableSet: {
          fontSize: '',
          lineHeight: '',
          marginTop: '',
          marginRight: '',
          marginBottom: '',
          marginLeft: '',
          border: '1',
          Proportion: '',
          checked: false
        },
        tableSelectTipShow: false,
        MmsPx: ''
      }
    },
    watch: {
      tableSet: {
        handler(newVal) {
          this.handleTableSetChange(newVal)
        },
        deep: true
      },
      'tableModel.mmWidth': function(newVal) {
        const MmsPx = this.MmsPx
        this.tableModel.pxWidth = parseInt(newVal * MmsPx)
      },
      'tableModel.mmHeight': function(newVal) {
        const MmsPx = this.MmsPx
        this.tableModel.pxHeight = parseInt(newVal * MmsPx)
      }
    },
    mounted() {
      // 配置顺序不可更改
      this.MmsPx = this.getOneMmsPx()
      this.initCustomButton()
      this.initHook()
      this.initDialog()
      this.getTemplateData()
    },
    methods: {
      getTemplateData() {
        this.templateType = this.$route.query.templateType
        if (this.templateType) {
          getPrinterType({ templateType: this.templateType }).then((res) => {
            const templateContent = JSON.parse(res.data.templateContent)
            setTimeout(() => {
              console.log(document.getElementsByTagName('iframe')[0].contentWindow)
              document.getElementsByTagName('iframe')[0].contentWindow.document.body.innerHTML = res.data.templateCode
              if (res.data.templateCode !== '' || res.data.templateCode !== null) {
                this.tableModel.pxWidth = templateContent.doc.width
                this.tableModel.pxHeight = templateContent.doc.height
                this.tableModel.mmWidth = templateContent.doc.mmWidth
                this.tableModel.mmHeight = templateContent.doc.mmHeight
              }
              this.handleTableReSize()
            }, 500)
          }).catch(() => {
            this.handleTableReSize()
            this.$message.error('模板获取失败！')
          })
        }
      },
      addCustom() {
        const addCustom = this.form.addCustom
        this.handleCustomButton({
          label: addCustom,
          val: addCustom
        })
        this.form.addCustom = ''
      },
      domClick() {
        const editor = this.editor
        const dom = editor
          .getSelection()
          .getStartElement()
          .getAscendant('table')
        const tableSet = {}
        if (dom) {
          // 得到当前dom
          this.tableSelectTipShow = true
          const table = editor
            .getSelection()
            .getStartElement()
            .getAscendant('table')
          // 样式处理
          const styleSet = table.$.style
          styleSet.fontSize === ''
            ? (tableSet.fontSize = '13')
            : (tableSet.fontSize = parseInt(styleSet.fontSize))
          styleSet.lineHeight === ''
            ? (tableSet.lineHeight = '10')
            : (tableSet.lineHeight = parseInt(styleSet.lineHeight))
          styleSet.marginTop === ''
            ? (tableSet.marginTop = '0')
            : (tableSet.marginTop = parseInt(styleSet.marginTop))
          styleSet.marginLeft === ''
            ? (tableSet.marginLeft = '0')
            : (tableSet.marginLeft = parseInt(styleSet.marginLeft))
          tableSet.border = table.$.border
          this.tableSet = tableSet
          // 获取表格比例
          this.toolProportion()
        } else {
          this.tableSelectTipShow = false
        }
      },
      handleTableReSize() {
        const pxHeight = this.tableModel.pxHeight
        const pxWidth = this.tableModel.pxWidth
        const body = document.getElementsByTagName('iframe')[0].contentWindow.document.body
        const iframe = document.getElementsByTagName('iframe')[0]
        iframe.width = pxWidth + 'px'
        iframe.height = pxHeight + 'px'
        iframe.style.width = pxWidth + 'px'
        iframe.style.height = pxHeight + 'px'
        iframe.style.margin = '0 auto'
        body.style.margin = 0
        this.$message({
          message: '模板尺寸成功设定！',
          type: 'success'
        })
      },
      handleCustomButton(item) {
        const that = this
        const { val } = item
        const editor = that.editor
        const dom = editor.getSelection().getStartElement().$
        dom.setAttribute('name', val)
        const nodeset = editor.getSelection().getStartElement()
        nodeset.setText(`【${val}】`)
      },
      handleAutoTable() {
        const editor = this.editor
        const table = editor
          .getSelection()
          .getStartElement()
          .getAscendant('table').$
        table.style.width = '100%'
      },

      printPreview() {
        const that = this
        this.dialogPrintPreview = true
        const nodeList = CKEDITOR.instances.editor.document.$.body.children
        var printpanel = htmlCompile(nodeList, this.tableModel, that, true)
        var orderDetails = []
        var source = {
          title: '�ٽ�����ȼ�����޹�˾�����ɹ���ⵥ',
          printDt: '2021-3-6',
          code: '123455555',
          storeName1: '��ʱ�ֿ�',
          marker1: '1',
          marker2: '1',
          marker3: '1',
          marker4: '1',
          marker5: '1',
          marker8: '˵��',
          details: orderDetails,
          footer1: 'f1',
          footer2: 'YSP-15? �� YSP-50?',
          footer3: 'YSP-15    ֻ��     YSP-50    ֻ',
          footer4: 'f4'
        }
        this.$nextTick(function() {
          if (!(source instanceof Array) && source instanceof Object) {
            new BeeDraw(true).draw(printpanel, source)
            // debugger;
          }
        })
      },
      Save() {
        const nodeList = CKEDITOR.instances.editor.document.$.body.children
        const templateContent = htmlCompile(nodeList, this.tableModel, this, false)
        templateContent.doc.mmWidth = this.tableModel.mmWidth,
        templateContent.doc.mmHeight = this.tableModel.mmHeight
        console.log(templateContent)
        const data = {
          templateType: this.templateType,
          templateContent: JSON.stringify(templateContent),
          templateCode: CKEDITOR.instances.editor.getData()
        }
        this.loading = true
        updatePrinterType(data).then(() => {
          this.$message({
            message: '模板保存成功',
            type: 'success'
          })
        })
        this.loading = false
      },
      Reset() {
        document.getElementsByTagName('iframe')[0].contentWindow.document.body.innerHTML = ''
      },
      pushInput() {
        const editor = this.editor
        editor.insertHtml(`<input type="text" name="customerName">`)
      },
      handleTableSetChange(newVal) {
        const {
          fontSize,
          lineHeight,
          marginTop,
          marginBottom,
          marginLeft,
          border
        } = newVal
        const editor = this.editor
        const table = editor
          .getSelection()
          .getStartElement()
          .getAscendant('table')
        if (table) {
          table.$.style.fontSize = `${fontSize}px`
          table.$.style.lineHeight = `${lineHeight}mm`
          table.$.style.marginTop = `${marginTop}mm`
          table.$.style.marginRight = `${marginLeft}mm`
          table.$.style.marginBottom = `${marginBottom}mm`
          table.$.style.marginLeft = `${marginLeft}mm`
          const computedWith = this.tableModel.pxWidth - parseInt(parseInt(marginLeft) * 2 * this.MmsPx)
          table.$.style.width = `${computedWith}px`

          if (border === 0) {
            table.$.classList.add('cke_show_border')
          } else {
            table.$.classList.remove('cke_show_border')
          }
          table.$.setAttribute('border', border)
        } else {
          this.$notify.error({
            title: '错误',
            message: '请先点击您要设置的表格！'
          })
        }
      },
      toolProportion() {
        //* ****************获取比例************************************************//
        const editor = this.editor
        const tbody = editor
          .getSelection()
          .getStartElement()
          .getAscendant('tbody')
        const nodeList = tbody.getChildren().$
        const table = editor
          .getSelection()
          .getStartElement()
          .getAscendant('table').$
        // 将dom节点转为数组
        const array = new Array()
        for (var i = 0; i < nodeList.length; i++) {
          if (nodeList[i].tagName === 'TR') {
            array.push(nodeList[i])
          }
        }
        const dataArray = array.sort(function(obj1, obj2) {
          var val1 = obj1.childElementCount
          var val2 = obj2.childElementCount
          if (val1 < val2) {
            return 1
          } else if (val1 > val2) {
            return -1
          } else {
            return 0
          }
        })
        // 取出数组
        const proportionAry = []
        for (let i = 0; i < dataArray[0].cells.length; i++) {
          const num = dataArray[0].cells[i].style.width
          proportionAry.push(num)
        }
        // console.log(proportionAry)
        const proportionAryLength = proportionAry.length
        // 处理比例数组，转为总数100的比例
        let pxSum = 0 // 获取reSize总数
        let proNum = 0 // 默认空格为空 分配比例总数
        const newProportion = proportionAry.map((item, index, value) => {
          if (item === '') {
            proNum += parseInt(100 / proportionAryLength)
            return parseInt(100 / proportionAryLength)
          } else {
            pxSum += parseInt(item)
            return item
          }
        })
        let NewproNum = 0
        // 处理数组元素 如果是非数字 利用累加器转为比例
        const Proportion = newProportion.map((item, index, value) => {
          if (isNaN(item)) {
            let intNum = parseInt(
              (parseInt(item) / pxSum) * (100 - proNum)
            )
            NewproNum += intNum
            if (index === proportionAryLength - 1) {
              intNum += parseInt(100 - NewproNum)
            }
            return intNum
          } else {
            NewproNum += item
            if (index === proportionAryLength - 1) {
              item += parseInt(100 - NewproNum)
            }
            return item
          }
        })
        const str = Proportion.join(',')
        // 投影
        this.tableSet.Proportion = str
        table.setAttribute('colwds', Proportion)
      },
      initHook() {
        const editor = CKEDITOR.replace('editor')
        this.editor = editor
        editor.config.resize_enabled = false

        editor.config.toolbarCanCollapse = true
        // editor.config.toolbarStartupExpanded = false;
        editor.on('instanceReady', () => {
          this.document.on('click', () => {
            this.domClick()
          })
          this.document.on('keyup', () => {})
          this.tableModel.mmWidth = 210
          this.tableModel.mmHeight = 297
        })
        editor.on('paste', (info) => {
          this.handlePaste(info)
        })
      },
      handlePaste(info) {
        const pasteText = info.dataValue
        const dom = document.createElement('div')
        dom.innerHTML = pasteText
      },
      initDialog() {
        CKEDITOR.on('dialogDefinition', (ev) => {
          const dialogName = ev.data.name
          const dialogDefinition = ev.data.definition
          // if(dialogName === 'table'){
          //   // let dialogContents = dialogDefinition.getContents("info");
          //   // console.log(dialogContents.elements[0].children.push(tableHtml))
          // }
          if (dialogName === 'textfield') {
            const genericElement = {
              type: 'text',
              id: 'style',
              label: '自定义样式'
            }
            const dialogContents = dialogDefinition.getContents('info')
            dialogContents.add(genericElement)
            const elements = dialogContents.elements
            elements.forEach((item) => {
              if (item.type && item.label === '类型') {
                const selectArray = [
                  ['文本', 'text'],
                  ['时间', 'date']
                ]
                item.items = selectArray
              }
            })
          }
          if (dialogName === 'cellProperties') {
            const dialogContents = dialogDefinition.getContents('info')

            const model2Html = [{
                                  type: 'select',
                                  id: 'type',
                                  label: '数据类型',
                                  default: 'text',
                                  items: [
                                    ['文本', 'text'],
                                    ['日期 yyyy-MM-dd HH:mm:ss', 'date1'],
                                    ['日期 yyyy-MM-dd HH:mm', 'date2'],
                                    ['日期 yyyy-MM-dd HH', 'date3'],
                                    ['日期 yyyy-MM-dd', 'date4'],
                                    ['日期 yy-MM-dd', 'date5']
                                  ],
                                  commit: function(a) {
                                    if (this.getValue() !== 'text') {
                                      a.setAttribute('type', this.getValue())
                                    }
                                  }
                                },
                                {
                                  type: 'select',
                                  id: 'Underline',
                                  label: '下划线',
                                  default: 'dis',
                                  items: [
                                    ['禁用', 'dis'],
                                    ['启用', 'open']
                                  ],
                                  commit: function(a) {
                                    if (this.getValue() === 'open') {
                                      a.setAttribute('Underline', 'open')
                                      a.$.style.borderBottom = '1px solid red'
                                    }
                                  }
                                }]

            dialogContents.elements[0].children[2].children = model2Html
          }
        })
      },
      getOneMmsPx() {
        const div = document.createElement('div')
        div.id = 'mm'
        div.style.width = '1mm'
        document.querySelector('body').appendChild(div)
        const mm1 = document.getElementById('mm').getBoundingClientRect()
        return mm1.width
      },
      initCustomButton() {
        this.listData = [
          {
            itemName: '客户信息',
            itemInfo: [
              { label: '客户编号', val: 'csmCode' },
              { label: '客户名称', val: 'csmName' },
              { label: '客户电话', val: 'csmPhone' },
              { label: '客户地址', val: 'csmAddress' },
              { label: '客户类型', val: 'csmType' },
              { label: '身份证号', val: 'sfzh' }
            ]
          },
          {
            itemName: '订单信息',
            itemInfo: [
              { label: '订单编号', val: 'orderCode' },
              { label: '下单时间', val: 'transactTime' },
              { label: '所属机构', val: 'orgName' },
              { label: '配送人', val: 'ownerName' },
              { label: '支付方式', val: 'payMethod' },
              { label: '订单金额', val: 'treceivables' },
              { label: '备注', val: 'remark' }
            ]
          },
          {
            itemName: '商品信息',
            itemInfo: [
              { label: '商品名称', val: 'goodsName' },
              { label: '商品规格', val: 'specName' },
              { label: '商品数量', val: 'gcount' },
              { label: '服务费', val: 'tip' },
              { label: '上楼费', val: 'fee2' },
              { label: '配送费', val: 'fee1' },
              { label: '商品价格', val: 'gprince' },
              { label: '实收金额', val: 'accReceivable' },
              { label: '应收金额', val: 'treceivable' }
            ]
          },
          {
            itemName: '押金信息',
            itemInfo: [
              { label: '押金单号', val: 'depositCode' },
              { label: '经办人', val: 'transactor' },
              { label: '经办时间', val: 'transactDt' },
              { label: '收款人', val: 'depReceiver' },
              { label: '总押金', val: 'totalDeposit' },
              { label: '总瓶数', val: 'totalCount' },
              { label: '押瓶机构', val: 'ckOrgName' },
              { label: '退瓶机构', val: 'returnOrgName' }
            ]
          }
        ]
      },
      getQueryVariable(variable) {
        var query = window.location.search.substring(1)
        var vars = query.split('&')
        for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split('=')
          if (pair[0] === variable) {
            return pair[1]
          }
        }
        return false
      }
    }
  }
</script>

<style lang="scss" scoped>
.edit-print {
  height: 130vh;
  margin: 0;
  background-color: #9bc1c9;
}
table {
  table-layout: fixed !important;
}
/deep/#cke_1_contents {
  height: 100vh !important;
  text-align: center;
  background-color: #dfdfdf;
}
/deep/#cke_1_contents table {
  word-break: break-all;
}
.headertool {
  position: fixed;
  z-index: 1000;
  display: block;
  width: 100%;
  padding: 10px;
  background: #9bc1c9;
}
.el-form-item {
  margin-bottom: 5px;
}
.el-dialog .el-dialog__body {
  padding: 20px;
  margin-top: 10px;
  background-color: #dfdfdf;
}
.el-dialog .el-dialog__body canvas {
  background-color: #FFF;
}
.el-card__body {
  padding: 10px 0;
}
.mainBox {
  position: relative;
  top: 50px;
  display: flex;
  justify-content: center;
  min-height: 80vh;
}
.mainBox_set {
  float: right;
}
.mainBox_child {
  padding: 5px;
  padding-top: 0;
}
.mainBox_left {
  width: 290px;
  min-width: 176px;
}
.mainBox_in {
  flex: 1;
}
.mainBox_right {
  width: 300px;
}
.mainBox_right .el-card .el-card__body {
  padding: 5px;
}
.mainBox_right input {
  width: 100%;
}
/deep/.el-card__body {
  padding: 10px;
}
/deep/.el-form-item__content {
  display: flex;
}
/deep/.el-input-group__append,
.el-input-group__prepend {
  padding: 0 10px;
}
.mainBox_left_minInput {
  width: 100px;
  margin-right: 5px;
}
.paddingcard {
  position: relative;
  margin-top: 5px;
}
.customButtonGroup {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  height: 77vh;
  overflow-y: auto;
  text-align: center;
}
.customButton {
  max-width: 86px;
  min-width: 75px;
  margin: 2px 1% 2px 0;
  flex: 1;
}
.fullInput {
  display: inline-block;
  max-width: 200px;
}
.otherLable {
  padding: 0 30px;
}
.otherLable_chikd {
  margin-bottom: 10px;
  text-align: left;
}
#cke_editor {
  margin: 0 auto;
}
#editor {
  width: 794px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
.el-input-group__append {
  padding: 0 5px;
}
#rightButton {
  float: right;
}

.foreach {
  background-color: #9bc1c9;
}
</style>

